var express = require('express');
var router = express.Router();
// var moment = require('moment');
// 引入模型
var listModel = require('./db');

// 解决跨域问题
router.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE');
  res.header('X-Powered-By', '3.2.1');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});

// 读取全部文章
router.get('/api/book', (req, res, next) => {
  let total
  let page
  listModel.find({}, (err, doc) => {
    if (err) {
      res.send({
        code: 0,
        msg: '请求失败'
      });
    } else {
      total = doc.length
      page = Math.ceil(total / 5)
    }
  })
  listModel
    .find({})
    .skip(5 * Number(req.query.page))
    .limit(5)
    .exec()
    .then(data => {
      res.json({
        code: 1,
        data: {
          data,
          page: {
            total: total,
            page: page,
            current_page: Number(req.query.page),
            limit: 5
          }
        }
      })
    })
});

// 读取单个文章详情
router.get('/api/detail/:id', (req, res, next) => {
  listModel.findById(req.params.id, (err, data) => {
    if (err) {
      res.send({
        code: 0,
        msg: '请求失败'
      });
    } else {
      res.send({
        code: 1,
        data
      });
    }
  });
});

// 写入文章
router.post('/api/book', (req, res, next) => {
  const editList = listModel({
    book_title: req.body.book_title,
    book_author: req.body.book_author,
    book_price: req.body.book_price,
    book_desc: req.body.book_desc,
    book_img: 'https://ocrjl5j3c.qnssl.com/zRweo2nWQQK1523259227.jpg'
  });
  editList.save((err, data) => {
    if (err) {
      res.send({
        code: 0,
        msg: '请求失败'
      });
    } else {
      res.send({
        code: 1,
        data
      });
    }
  });
});

// 删除文章
router.delete('/api/book/:id', (req, res, next) => {
  listModel.findById(req.params.id, (res, data) => {
    data.remove((res, data) => {
      res.send({
        code: 1,
        msg: '删除成功!'
      });
      res.end();
    });
  });
});

// 编辑文章
router.post('/api/book/:id', (req, res, next) => {
  listModel.findById(req.params.id, (res, data) => {
    data.book_title = req.body.book_title;
    data.book_author = req.body.book_author;
    data.book_price = req.body.book_price;
    data.book_desc = req.body.book_desc;
    data.book_img = 'https://ocrjl5j3c.qnssl.com/zRweo2nWQQK1523259227.jpg';

    data.save((err, data) => {
      if (err) {
        res.send({
          code: 0,
          msg: '请求失败'
        });
      } else {
        res.send({
          code: 1,
          data
        });
      }
    });
  });
});
module.exports = router;
